package com.raysdata.smartcity.web.sys;

import com.alibaba.fastjson.JSON;
import com.raysdata.smartcity.HelperClazz;
import com.raysdata.smartcity.dao.sys.AttachDao;
import com.raysdata.smartcity.dto.Attachment;
import com.raysdata.smartcity.web.BaseController;
import com.raysdata.smartcity.web.common.Property;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;

/**
 * Created by bh on 2016/11/11.
 * 附件controller
 */
@Controller
@RequestMapping(value = "/attach")
public class AttachController  extends BaseController{

    @Autowired
    public AttachDao attachDao;

    /**
     * 保存文件到数据库
     * @param oldName
     * @param newName
     * @param f_type
     * @param path
     * @return
     */
    public String save(String oldName,String newName,String f_type,String path){
        Attachment attachment=new Attachment();
        String id= UUID.randomUUID().toString().trim().replaceAll("-", "");
        attachment.setAttachment_id(id);
        attachment.setName(oldName);
        attachment.setCode(newName);
        attachment.setF_type(f_type);
        attachment.setPath(path);
        attachment.setStatus("0");
        attachDao.insert(attachment);
        return id;
    }

    /**
     * 删除附件
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping(value = "/delete")
    public void delete(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
        String id=request.getParameter("id");
        Attachment attachment=attachDao.getAttachmentByid(id);
        int result=attachDao.delete(id);
        if(result!=-1){
            File file = new File(attachment.getPath());
            // 路径为文件且不为空则进行删除
            if (file.isFile() && file.exists()) {
                file.delete();
                response.getWriter().write("{\"success\":true}");
            }
        }else{
            response.getWriter().write("{\"files\":[{\"error\":\"文件删除异常\"}]}");
        }

    }

    /**
     * 下载附件
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping(value = "/download")
    public void download(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
        //PrintWriter out = response.getWriter();

        //out.println(getServletContext().getRealPath("/"));

        String id=request.getParameter("id");
        Attachment attachment=attachDao.getAttachmentByid(id);

        //设置向浏览器端传送的文件格式
        response.setContentType("bin");

        String filename = attachment.getName();
        /******
         * 设置文件不在浏览器中直接打开，而且通过filename参数可以设置建议保存文件名，这个文件名会出现在save as文件框
         * 文件名中，作为默认保存名。如果不设置的话，则会把Servlet的名称作为默认的保存名
         */
        filename = new String(filename.getBytes(), "ISO-8859-1");
        response.setHeader("Content-disposition","attachment; filename="+filename);

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try{
            bis = new BufferedInputStream(new FileInputStream(attachment.getPath()));
            bos = new BufferedOutputStream(response.getOutputStream());

            byte[] buff = new byte[bis.available()];
            int bytesRead = 0;

            response.addHeader("Content-Length", "" + bis.available());

            while(-1 !=(bytesRead = (bis.read(buff, 0, buff.length)))){
                bos.write(buff, 0, buff.length);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(bis != null){
                bis.close();
            }
            if(bos != null){
                bos.close();
            }
        }
    }

    /**
     * 上传文件方法
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping(value = "/upload")
    public void upload(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //得到上传文件的保存目录，将上传的文件存放于WEB-INF目录下，不允许外界直接访问，保证上传文件的安全
        //String path = getServletConfig().getServletContext().getRealPath("");
        //String savePath = this.getServletContext().getRealPath("/WEB-INF/upload");

        String savePath="";
        String f_type="";
        //消息提示
        String message="{\"files\":[";
        String filename="";
        String fileOldName="";
        try{
            //使用Apache文件上传组件处理文件上传步骤：
            //1、创建一个DiskFileItemFactory工厂
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //2、创建一个文件上传解析器
            ServletFileUpload upload = new ServletFileUpload(factory);
            //解决上传文件名的中文乱码
            upload.setHeaderEncoding("UTF-8");
            //3、判断提交上来的数据是否是上传表单的数据
            if(!ServletFileUpload.isMultipartContent(request)){
                //按照传统方式获取数据
                return;
            }
            //4、使用ServletFileUpload解析器解析上传数据，解析结果返回的是一个List<FileItem>集合，每一个FileItem对应一个Form表单的输入项
            List<FileItem> list = upload.parseRequest(request);
            for(FileItem item : list){
                //如果fileitem中封装的是普通输入项的数据
                if(item.isFormField()){
                    String name = item.getFieldName();
                    //解决普通输入项的数据的中文乱码问题
                    String value = item.getString("UTF-8");
                    //value = new String(value.getBytes("iso8859-1"),"UTF-8");
                    if(name.equals("f_type")){
                        f_type=value;
                        Property property=new Property();
                        try {
                            savePath=property.getProperty(f_type);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        File file = new File(savePath);
                        //判断上传文件的保存目录是否存在
                        if (!file.exists() && !file.isDirectory()) {
                            System.out.println(savePath+"目录不存在，需要创建");
                            //创建目录
                            file.mkdir();
                        }
                    }
                }else{//如果fileitem中封装的是上传文件
                    //得到上传的文件名称，
                    filename = item.getName();
                    System.out.println(filename);
                    if(filename==null || filename.trim().equals("")){
                        continue;
                    }
                    //注意：不同的浏览器提交的文件名是不一样的，有些浏览器提交上来的文件名是带有路径的，如：  c:\a\b\1.txt，而有些只是单纯的文件名，如：1.txt
                    //处理获取到的上传文件的文件名的路径部分，只保留文件名部分
                    filename = filename.substring(filename.lastIndexOf("\\")+1);
                    fileOldName=filename.substring(filename.lastIndexOf("\\")+1);
                    String [] files=filename.split("\\.");

                    filename = System.currentTimeMillis()+"."+files[files.length-1];
                    //获取item中的上传文件的输入流
                    InputStream in = item.getInputStream();
                    //创建一个文件输出流
                    FileOutputStream out = new FileOutputStream(savePath + filename);
                    //创建一个缓冲区
                    byte buffer[] = new byte[1024];
                    //判断输入流中的数据是否已经读完的标识
                    int len = 0;
                    //循环将输入流读入到缓冲区当中，(len=in.read(buffer))>0就表示in里面还有数据
                    while((len=in.read(buffer))>0){
                        //使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中
                        out.write(buffer, 0, len);
                    }
                    //关闭输入流
                    in.close();
                    //关闭输出流
                    out.close();
                    //删除处理文件上传时生成的临时文件
                    item.delete();
                    String id=this.save(fileOldName,filename,f_type,savePath + filename);
                    message += "{\"name\":\""+fileOldName+"\",\"id\":\""+id
                            +"\",\"deleteUrl\":\"/attach/delete?id="+id
                            +"\",\"deleteType\":\"get\",\"url\":\"/attach/download?id="+id+"\"}";
                }
            }
        }catch (Exception e) {
            message= "{\"success\":false}";
            e.printStackTrace();
        }
        message+="]}";
        response.setHeader("Content-type", "text/json;charset=UTF-8");
        response.getWriter().write(message);
        //request.getRequestDispatcher("/message.jsp").forward(request, response);
    }

    @RequestMapping(value = "/getAttachByFid")
    public void getAttachByFid(HttpServletRequest request, HttpServletResponse response){
        String fid=request.getParameter("fid");
        List<Attachment> attachmentList=attachDao.getAllByFid(fid);
        HelperClazz.renderJson(response, JSON.toJSONString(attachmentList));
    }


    /**
     * 下载附件
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping(value = "/editorDownload")
    public void downloadChart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String realPath =request.getSession().getServletContext().getRealPath("");

        String projname=request.getContextPath();

        //设置向浏览器端传送的文件格式
        response.setContentType("bin");
        String path=request.getParameter("path");
        path=realPath+path.replace(projname+"/","");

        String filename = request.getParameter("filename");
        if(!HelperClazz.isEmpty(filename)){
            filename = filename.replace(" ","");// 去除空格
        }
        /******
         * 设置文件不在浏览器中直接打开，而且通过filename参数可以设置建议保存文件名，这个文件名会出现在save as文件框
         * 文件名中，作为默认保存名。如果不设置的话，则会把Servlet的名称作为默认的保存名
         */
        filename = new String(filename.getBytes(), "ISO-8859-1");
        response.setHeader("Content-disposition", "attachment; filename=" + filename);

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            bis = new BufferedInputStream(new FileInputStream(path));
            bos = new BufferedOutputStream(response.getOutputStream());

            byte[] buff = new byte[bis.available()];
            int bytesRead = 0;

            response.addHeader("Content-Length", "" + bis.available());

            while (-1 != (bytesRead = (bis.read(buff, 0, buff.length)))) {
                bos.write(buff, 0, buff.length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                bis.close();
            }
            if (bos != null) {
                bos.close();
            }
        }
    }
}
